package com.ms.core.admin.admin.controller;

import com.ms.base.comm.util.FrameUtil;
import com.ms.base.web.mvc.BaseViewController;
import com.ms.base.web.mvc.IModuleViewController;
import com.ms.base.web.mvc.WebUtil;
import com.ms.core.admin.admin.dto.AdminLoginDataDto;
import com.ms.core.admin.admin.util.LoginUtil;
import com.ms.core.api.admin.*;
import com.ms.core.comm.admin.dto.AdminLoginRequest;
import com.ms.core.comm.admin.dto.AdminLoginResponse;
import com.ms.core.comm.admin.model.AdminRoleMenuModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <b>description</b>：登录方法 <br>
 * <b>time</b>：2018-08-14 09:20 <br>
 * <b>author</b>： ready likun_557@163.com
 */
@Controller
@RequestMapping("/" + AdminLoginController.MODULE_NAME + "/" + AdminLoginController.CONTROLLER_NAME)
public class AdminLoginController extends BaseViewController implements IModuleViewController {

    public static final String MODULE_NAME = "admin";
    public static final String CONTROLLER_NAME = "adminLogin";

    @Autowired
    private AdminLoginClient adminLoginClient;

    /**
     * 登录
     *
     * @param request
     * @return
     */
    @RequestMapping("")
    public String login(HttpServletRequest request, @RequestParam("name") String name, @RequestParam("password") String password) throws Exception {
        if (LoginUtil.isLogin(request)) {
            return "redirect:" + WebUtil.getControllerPath(MainController.MODULE_NAME, MainController.CONTROLLER_NAME, MainController.INDEX_METHOD);
        }
        AdminLoginResponse adminLoginResponse = this.adminLoginClient.login(AdminLoginRequest.builder().name(name).password(password).ip(WebUtil.getIp(request)).build()).okData();
        List<Long> userMenuIdList = FrameUtil.getBeanFieldValues(adminLoginResponse.getAdminRoleMenuModelList(), AdminRoleMenuModel.MENU_ID_COL);
        AdminLoginDataDto adminLoginDataDto = LoginUtil.build(adminLoginResponse.getAdminModel(), adminLoginResponse.getAdminMenuModelList(), userMenuIdList);
        LoginUtil.putSession(request, adminLoginDataDto);
        return this.successView(request, "登录成功!", WebUtil.getControllerPath(MainController.MODULE_NAME, MainController.CONTROLLER_NAME, MainController.INDEX_METHOD));
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping("/exit")
    public String exit(HttpServletRequest request) {
        LoginUtil.loginOut(request);
        return this.successView(request, "退出成功!", "");
    }

    @Override
    public String moduleName() {
        return MODULE_NAME;
    }

    @Override
    public String controllerName() {
        return AdminLoginController.CONTROLLER_NAME;
    }
}
